package org.gd.hellojaxb.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;

/**
 * @author Gorhover
 * @version 3.0
 */
public final class UnMarshall {

    private UnMarshall() {
        super();
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(InputStream source, Class<T> clazz, MarshallProperties...props)
            throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        if(props != null) {
            for (MarshallProperties prop: props) {
                if (prop != null) {
                    unmarshaller.setProperty(prop.getKey(), prop.getValue());
                }
            }
        }
        return (T) unmarshaller.unmarshal(source);
    }

    public static <T> T unmarshal(String source, Class<T> clazz, MarshallProperties...props)
            throws JAXBException {
        return unmarshal(StringUtils.StringToInputStream(source), clazz, props);
    }
}
